package jmine.tec.extensions.services.rs;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import jmine.tec.test.Builder;

/**
 * Builder for services pages
 * 
 * @author lundberg
 */
public class ServicesPagesRSBuilder implements Builder<List<ServicesPageRS>> {

    private List<ServicesPageRS> pages = new ArrayList<ServicesPageRS>();

    private ServicesPageRS currentPage;

    private ServiceRS currentService;

    /**
     * @return ServicesPagesRSBuilder
     */
    public static ServicesPagesRSBuilder services() {
        return new ServicesPagesRSBuilder();
    }

    /**
     * Inicia a construção de um serviço
     * 
     * @param action action
     * @param name name
     * @return ServicesPagesRSBuilder
     */
    public ServicesPagesRSBuilder service(String action, String name) {
        this.closeService();
        this.currentService = new ServiceRS();
        this.currentService.setAction(action);
        this.currentService.setName(name);
        return this;
    }

    /**
     * Adiciona o parâmetro ao serviço sendo construído para execução.
     * 
     * @param key key
     * @param value value
     * @return ServicesPagesRSBuilder
     */
    public ServicesPagesRSBuilder put(String key, String value) {
        if (this.currentService == null) {
            throw new IllegalStateException("Primeiro é necessário invocar startService para depois definir os parâmetros do serviço.");
        }
        this.currentService.getParameters().put(key, value);
        return this;
    }

    /**
     * Fecha o serviço criado, adicionando-o à lista para execução.
     * 
     * @return ServicesPagesRSBuilder
     */
    public ServicesPagesRSBuilder closeService() {
        if (this.currentService != null) {
            if (this.currentPage == null) {
                this.currentPage = new ServicesPageRS();
            }
            this.currentPage.getServices().add(this.currentService);
            this.currentService = null;
        }
        return this;
    }

    /**
     * Closes the services page
     * 
     * @return ServicesPagesRSBuilder
     */
    public ServicesPagesRSBuilder closePage() {
        this.closeService();
        if (this.currentPage != null) {
            this.pages.add(this.currentPage);
            this.currentPage = null;
        }
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public List<ServicesPageRS> build() {
        this.closePage();
        return Collections.unmodifiableList(this.pages);
    }
}
